const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

function debounce(func,duration = 500){
  let tiemId;
  return function(){
    const context = this;
    const args = arguments;
    clearTimeout(tiemId);
    tiemId = setTimeout(()=>{
        func.apply(context,args)
    },duration)
  }
}

 function throttle(func, delay) {
  let timer = null;
  let previous = 0;

  return function() {
    const context = this;
    const args = arguments;
    const now = Date.now();

    if (now - previous > delay) {
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
      func.apply(context, args);
      previous = now;
    } else if (!timer) {
      timer = setTimeout(() => {
        func.apply(context, args);
        previous = now;
        timer = null;
      }, delay - (now - previous));
    }
  };
}

module.exports = {
  formatTime,
  debounce,
  throttle
}
